package cn.seaboot.admin.mvc.response;

import cn.seaboot.admin.mvc.Result;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.function.Function;

/**
 * jackson 转换器
 *
 * @author Mr.css
 * @version 2022-04-29 10:20
 */
public class JacksonModelAndViewConverter implements Function<Result, ModelAndView> {
    /**
     * 500 错误是通用的，这里优化一下序列化方法
     */
    private final ModelAndView unknown;

    public JacksonModelAndViewConverter() {
        Result result = Result.INTERNAL_SERVER_ERROR;
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.addStaticAttribute("code", result.getCode());
        view.addStaticAttribute("data", result.getData());
        this.unknown = new ModelAndView(view);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ModelAndView apply(Result result) {
        if (result == Result.INTERNAL_SERVER_ERROR) {
            return unknown;
        } else {
            MappingJackson2JsonView view = new MappingJackson2JsonView();
            view.addStaticAttribute("code", result.getCode());
            view.addStaticAttribute("data", result.getData());
            return new ModelAndView(view);
        }
    }
}
